<template>
  <div class="min-h-screen bg-slate-50">
    <TopBar />
    <div class="container mx-auto px-4 py-8">
      <!-- 页面标题 -->
      <div class="mb-6">
        <h1 class="text-2xl font-bold text-gray-800">我的订单</h1>
      </div>

      <!-- 搜索和筛选 -->
      <div class="flex flex-col md:flex-row justify-between items-start md:items-center gap-4 mb-6">
        <div class="w-full md:w-1/2">
          <div class="flex h-12">
            <input type="search" class="flex-1 px-4 border border-gray-300 rounded-l-lg focus:outline-none"
              placeholder="商品名称/编号/订单号">
            <button class="px-6 bg-gray-200 hover:bg-gray-300 rounded-r-lg transition-colors">
              订单搜索
            </button>
          </div>
        </div>

        <div class="w-full md:w-auto">
          <el-date-picker v-model="dateRange" type="daterange" range-separator="至" start-placeholder="开始日期"
            end-placeholder="结束日期" size="default" />
        </div>
      </div>

      <!-- 订单列表 -->
      <div class="bg-white rounded-xl shadow-sm overflow-hidden">
        <div v-if="ordersData.length === 0" class="py-16 text-center">
          <el-icon size="60" class="text-gray-300">
            <Document />
          </el-icon>
          <p class="mt-4 text-gray-500">暂无订单记录</p>
          <button
            class="mt-4 px-6 py-2 bg-red-500 text-white rounded-lg hover:bg-red-600 transition-colors cursor-pointer"
            @click="$router.push('/index')">
            立即购物
          </button>
        </div>

        <div v-else>
          <div v-for="(orderGroup, index) in ordersData" :key="index" class="border-b border-gray-100 mb-5 last:m-0">
            <!-- 订单头部信息 -->
            <div class="bg-gray-50 px-6 py-3 flex flex-col md:flex-row justify-between items-start md:items-center">
              <div class="flex flex-col md:flex-row gap-4 mb-2 md:mb-0">
                <span class="text-gray-600">{{ formatDate(orderGroup.createTime) }}</span>
                <span class="text-gray-500">订单号：{{ orderGroup.orderId }}</span>
                <div class="flex items-center text-gray-600">
                  <el-icon class="mr-1">
                    <Shop />
                  </el-icon>
                  <span>商城</span>
                </div>
              </div>
              <div class="flex items-center">
                <button class="text-gray-400 hover:text-red-500 transition-colors"
                  @click="deleteOrder(orderGroup.orderId)">
                  <el-icon>
                    <Delete />
                  </el-icon>
                </button>
              </div>
            </div>

            <!-- 订单商品信息 -->
            <template v-if="orderItem">
              <div class="px-6 py-4 border-t border-gray-100">
                <div class="flex flex-col md:flex-row gap-4">
                  <!-- 商品信息 -->
                  <div class="flex-1 flex items-center">
                    <div class="w-20 h-20 bg-gray-100 rounded-lg overflow-hidden flex-shrink-0">
                      <img src="https://picsum.photos/200/200" alt="商品图片" class="w-full h-full object-cover">
                    </div>
                    <div class="ml-4">
                      <h3 class="font-medium text-gray-800 mb-1 line-clamp-2">{{ orderItem.skuName }}</h3>
                      <p class="text-sm text-gray-500">{{ orderItem.skuAttr }}</p>
                    </div>
                  </div>
                  <!-- 数量 -->
                  <div class="w-full md:w-auto text-center py-2 md:py-0">
                    <span class="text-gray-600">×{{ orderItem.purchaseQuantity }}</span>
                  </div>
                  <!-- 收货人 -->
                  <div class="w-full md:w-auto text-center py-2 md:py-0">
                    <div class="flex items-center justify-center">
                      <span class="text-gray-600">收货人</span>
                      <el-icon class="ml-1 text-gray-400">
                        <User />
                      </el-icon>
                    </div>
                  </div>
                  <!-- 金额 -->
                  <div class="w-full md:w-auto text-center py-2 md:py-0 font-medium text-red-500">
                    ￥{{ orderItem.skuPrice }}
                  </div>
                  <!-- 状态 -->
                  <div class="w-full md:w-auto text-center py-2 md:py-0">
                    <span class="px-2 py-1 rounded-full text-xs font-medium"
                      :class="getStatusClass(getStatusText(orderGroup.orderStatus))">{{
                        getStatusText(orderGroup.orderStatus) }}</span>
                  </div>
                  <!-- 操作 -->
                  <div class="w-full md:w-auto text-center py-2 md:py-0">
                    <div class="flex flex-col sm:flex-row justify-center gap-2">
                      <el-button v-if="orderGroup.orderStatus === 4" type="warning" size="small"
                        @click="buyAgain(orderItem)">
                        再买一单
                      </el-button>
                      <el-button v-if="orderGroup.orderStatus === 4" size="small" @click="addToCart(orderItem)">
                        加入购物车
                      </el-button>
                      <el-button v-if="orderGroup.orderStatus === 1" type="primary" size="small"
                        @click="payOrder(orderGroup.orderId)">
                        立即付款
                      </el-button>
                      <el-button v-if="orderGroup.orderStatus === 3" size="small"
                        @click="confirmReceipt(orderGroup.orderId)">
                        确认收货
                      </el-button>
                    </div>
                  </div>
                </div>
              </div>
            </template>

            <!-- 如果没有订单商品信息，显示基本信息 -->
            <div v-else class="px-6 py-4 border-t border-gray-100">
              <div class="text-center text-gray-500">
                <p>订单金额：￥{{ orderGroup.orderAmount }}</p>
                <p v-if="orderGroup.orderNote" class="mt-2">备注：{{ orderGroup.orderNote }}</p>
              </div>
            </div>

            <!-- 订单汇总 -->
            <div class="px-6 py-3 bg-gray-50 border-t border-gray-100 flex justify-end">
              <div class="text-right">
                <div class="text-sm text-gray-600">
                  共 {{ orderItem ? orderItem.purchaseQuantity : 1 }} 件商品 | 合计：<span class="font-bold text-red-500">￥{{
                    orderGroup.orderAmount }}</span>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
    <Aside />
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue';
import { useRouter } from 'vue-router';
import Aside from '@/components/Aside.vue';
import TopBar from '@/components/TopBar.vue';
import { getOrderApi, getOrderItemApi } from '@/apis/order';

const router = useRouter();
const ordersData = ref([]);
const orderItem = ref(null);
const dateRange = ref([]);

// 获取订单数据
const getOrderData = async () => {
  try {
    const res = await getOrderApi();
    console.log('订单数据:', res.data);
    ordersData.value = res.data || [];

    // 如果有订单数据，获取第一个订单的商品详情
    if (res.data && res.data.length > 0) {
      const res2 = await getOrderItemApi(res.data[0].orderId);
      console.log('订单商品详情:', res2.data);
      orderItem.value = res2.data || null;
    }
  } catch (error) {
    console.error('获取订单数据失败:', error);
  }
};

// 格式化日期
const formatDate = (dateString) => {
  if (!dateString) return '';
  const date = new Date(dateString);
  return date.toLocaleDateString('zh-CN') + ' ' + date.toLocaleTimeString('zh-CN', { hour12: false });
};

// 获取状态文本
const getStatusText = (status) => {
  const statusMap = {
    1: '待付款',
    2: '待发货',
    3: '待收货',
    4: '已完成',
    5: '已取消'
  };
  return statusMap[status] || '未知状态';
};

// 订单状态样式
const getStatusClass = (status) => {
  const statusMap = {
    '待付款': 'bg-yellow-100 text-yellow-800',
    '待发货': 'bg-blue-100 text-blue-800',
    '待收货': 'bg-orange-100 text-orange-800',
    '已完成': 'bg-green-100 text-green-800',
    '已取消': 'bg-gray-100 text-gray-800'
  };
  return statusMap[status] || 'bg-gray-100 text-gray-800';
};

// 删除订单
const deleteOrder = async (orderId) => {
  try {
    console.log('删除订单:', orderId);
    // 这里需要调用删除订单的API
  } catch (error) {
    console.error('删除订单失败:', error);
  }
};

// 再买一单
const buyAgain = (item) => {
  console.log('再买一单:', item);
  router.push(`/item/${item.spuId}`);
};

// 加入购物车
const addToCart = async (item) => {
  try {
    console.log('加入购物车:', item);
    // 这里需要调用加入购物车的API
  } catch (error) {
    console.error('加入购物车失败:', error);
  }
};

// 立即付款
const payOrder = async (orderId) => {
  try {
    console.log('立即付款:', orderId);
    router.push(`/buy?orderId=${orderId}`);
  } catch (error) {
    console.error('支付失败:', error);
  }
};

// 确认收货
const confirmReceipt = async (orderId) => {
  try {
    console.log('确认收货:', orderId);
    // 这里需要调用确认收货的API
  } catch (error) {
    console.error('确认收货失败:', error);
  }
};

onMounted(() => {
  getOrderData();
});
</script>

<style lang="scss" scoped>
// 订单状态标签样式
.order-status {
  display: inline-block;
  padding: 0.25rem 0.75rem;
  border-radius: 999px;
  font-size: 0.75rem;
  font-weight: 500;
}
</style>